package com.demo.netty.mulport;

import org.apache.log4j.Logger;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class WebsocketHeartbeatHandler extends ChannelDuplexHandler {
	
    private static final Logger logger = Logger.getLogger(WebsocketHeartbeatHandler.class);


	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		super.userEventTriggered(ctx, evt);
		if (evt instanceof IdleStateEvent) {
			{
				IdleStateEvent e = (IdleStateEvent) evt;
				if (e.state() == IdleState.READER_IDLE) {
					ctx.close();
					logger.info("userEventTriggered.READER_IDLE.");
				} else if (e.state() == IdleState.WRITER_IDLE) {
					ctx.writeAndFlush(new PingWebSocketFrame());
					logger.info("userEventTriggered.WRITER_IDLE.");
				}
			}

		}

	}

}
